package com.wangzeqi.changliaoba.contacts;

import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;

import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMContactManager;
import com.easemob.exceptions.EaseMobException;
import com.wangzeqi.changliaba.dao.ContactsEntity;
import com.wangzeqi.changliaba.dao.ContactsEntityDao;
import com.wangzeqi.changliaoba.R;
import com.wangzeqi.changliaoba.base.BaseFragment;
import com.wangzeqi.changliaoba.messege.MyClick;
import com.wangzeqi.changliaoba.singleton.AllSingleTon;
import com.wangzeqi.custom.ClearEditText;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import de.greenrobot.dao.query.QueryBuilder;

/**
 * Created by dllo on 16/3/1.
 */
public class ContactsFragment extends BaseFragment implements MyClick {
    private ListView sortListView;
    private SideBar sideBar;
    private TextView dialog;
    private AdapterContact adapter;
    private ContentResolver cr;
    private ClearEditText mClearEditText;
    protected NotifyDataBroadcast receiver;
    private List<String> usernames;
    /**
     * 汉字转换成拼音的类
     */
    private CharacterParser characterParser;
    private List<SortModel> SourceDateList;
    private List<ContactsEntity> contactData;
    /**
     * 根据拼音来排列ListView里面的数据类
     */
    private PinyinComparator pinyinComparator;

    int j = 1;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.contact_layout, null);
        ContactActivity.setMyClick(this);
        sideBar = (SideBar) view.findViewById(R.id.sidrbar);
        dialog = (TextView) view.findViewById(R.id.dialog);
        sortListView = (ListView) view.findViewById(R.id.country_lvcountry);
        mClearEditText = (ClearEditText) view.findViewById(R.id.filter_edit);

        return view;


    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        //防止被T后，没点确定按钮然后按了home键，长期在后台又进app导致的crash
        if (savedInstanceState != null && savedInstanceState.getBoolean("isConflict", false))
            return;
        super.onActivityCreated(savedInstanceState);

        EMChatManager.getInstance().getChatOptions().setUseRoster(true);
        //组册动态广播
        IntentFilter filter = new IntentFilter("com.wangzeqi.changliaoba.contacts.NOTIFY");
        receiver = new NotifyDataBroadcast();
        getActivity().registerReceiver(receiver, filter);
        initData();
    }

    private void initData() {
        //实例化汉字转拼音类
        characterParser = CharacterParser.getInstance();
        pinyinComparator = new PinyinComparator();
        sideBar.setTextView(dialog);
        //设置右侧触摸监听
        sideBar.setOnTouchingLetterChangedListener(new SideBar.OnTouchingLetterChangedListener() {
            @Override
            public void onTouchingLetterChanged(String s) {
                //该字母首次出现的位置
                int position = adapter.getPositionForSection(s.charAt(0));
                if (position != -1) {
                    sortListView.setSelection(position);
                }
            }
        });
        forAddData();
        // 根据a-z进行排序源数据
        Collections.sort(SourceDateList, pinyinComparator);
        adapter = new AdapterContact(getActivity(), SourceDateList);
        sortListView.setAdapter(adapter);

        //根据输入框输入值的改变来过滤搜索
        mClearEditText.addTextChangedListener(new TextWatcher() {

                                                  @Override
                                                  public void onTextChanged(CharSequence s, int start, int before, int count) {
                                                      //当输入框里面的值为空，更新为原来的列表，否则为过滤数据列表
                                                      filterData(s.toString());
                                                  }

                                                  @Override
                                                  public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                                                  }

                                                  @Override
                                                  public void afterTextChanged(Editable s) {
                                                  }
                                              }
        );
    }

    @Override
    public void onResume() {
        super.onResume();
        adapter.notifyDataSetChanged();
    }

    private void forAddData() {
            try {
                usernames = EMContactManager.getInstance().getContactUserNames();//需异步执行
                if (usernames != null && usernames.size() > 0) {
                    String[] arg = new String[usernames.size()];


                    for (int i = 0; i < usernames.size(); i++) {
                        arg[i] = usernames.get(i);
                        ContactsEntity data = new ContactsEntity(usernames.get(i), EMChatManager.getInstance().getCurrentUser());
                        AllSingleTon.getOurInstance().getDaoSession().getContactsEntityDao().insertOrReplace(data);
                    }
                    SourceDateList = filledData(arg);

                } else {
                    SourceDateList = filledData(getResources().getStringArray(R.array.date));
                }

            } catch (EaseMobException e) {
                e.printStackTrace();
            }
    }

    /**
     * 为ListView填充数据
     *
     * @param date
     * @return
     */
    private List<SortModel> filledData(String[] date) {
        List<SortModel> mSortList = new ArrayList<SortModel>();

        for (int i = 0; i < date.length; i++) {
            SortModel sortModel = new SortModel();
            sortModel.setName(date[i]);
            //汉字转换成拼音
            String pinyin = characterParser.getSelling(date[i]);
            String sortString = pinyin.substring(0, 1).toUpperCase();

            // 正则表达式，判断首字母是否是英文字母
            if (sortString.matches("[A-Z]")) {
                sortModel.setSortLetters(sortString.toUpperCase());
            } else {
                sortModel.setSortLetters("#");
            }

            mSortList.add(sortModel);
        }
        return mSortList;

    }

    /**
     * 根据输入框中的值来过滤数据并更新ListView
     *
     * @param filterStr
     */


    private void filterData(String filterStr) {
        List<SortModel> filterDateList = new ArrayList<SortModel>();

        if (TextUtils.isEmpty(filterStr)) {
            filterDateList = SourceDateList;
        } else {
            filterDateList.clear();
            for (SortModel sortModel : SourceDateList) {
                String name = sortModel.getName();
                if (name.indexOf(filterStr.toString()) != -1 || characterParser.getSelling(name).startsWith(filterStr.toString())) {
                    filterDateList.add(sortModel);
                }
            }
        }
        Collections.sort(filterDateList, pinyinComparator);
        adapter.updateListView(filterDateList);
        adapter.notifyDataSetChanged();
    }

    @Override
    public void onClick(int position, String string) {

    }

    @Override
    public void ForwardMessegeChanged() {

    }

    @Override
    public void deleteFriend(String name) {
        for (int i = 0; i < SourceDateList.size(); i++) {

            if (name.equals(SourceDateList.get(i).getName())) {
                SourceDateList.remove(i);
            }
        }
        adapter.notifyDataSetChanged();
    }

    @Override
    public void sendPictures(ArrayList<String> datas) {

    }

    class NotifyDataBroadcast extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {

        }
    }
}
